package model

import (
	"ci-control-backend/common"
	xorm_logrus "github.com/RuiFG/xorm-logrus"
	_ "github.com/go-sql-driver/mysql"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"os"
	"xorm.io/xorm"
	"xorm.io/xorm/names"
)

// DB 单例模式
var DB *xorm.Engine

func CreateRootAccountIfNeed() error {
	count, err := DB.Where("id = ?", 1).Count(&User{})
	if err != nil {
		return err
	}
	if count < 1 {
		logrus.Infoln("no user exists, create a root user for you: username is root, password is root123")
		rootUser := &User{
			Model: Model{
				ID: 1,
			},
			Username: "root",
			Password: "root123",
		}
		_, err := rootUser.Insert()
		if err != nil {
			return err
		}
	}
	return nil
}

func ResetHostOnlineStatus() error {
	//_, err := DB.Exec("update host set online_status = ?", common.OFFLINE)
	_, err := DB.MustCols("online_status").Update(&Host{OnlineStatus: common.OFFLINE})
	return errors.WithStack(err)
}

func Setup() (err error) {

	var db *xorm.Engine
	if os.Getenv("SQL_DSN") != "" {
		// Use MySQL
		logrus.Infoln("using MySQL as database")
		db, err = xorm.NewEngine("mysql", os.Getenv("SQL_DSN"))
		if err != nil {
			return err
		}
		logger := logrus.New()
		logger.SetOutput(os.Stdout)
		logger.SetReportCaller(true)
		logger.SetFormatter(new(common.SQLLogFormatter))
		db.SetMapper(names.GonicMapper{})
		db.SetLogger(xorm_logrus.NewLogrusLogger2(logger))
		db.ShowSQL(true)
	} else {
		return errors.New("SQL_DSN not set")
	}

	logrus.Infoln("database connected")

	// 自动建表
	err = db.Sync(new(User), new(Host), new(Plan), new(Record))
	if err != nil {
		return err
	}

	DB = db

	err = CreateRootAccountIfNeed()
	if err != nil {
		return err
	}

	err = ResetHostOnlineStatus()
	if err != nil {
		return err
	}

	return nil
}
